package cn.addr.user.dao;

import java.util.List;
import java.util.UUID;

import org.hibernate.Query;
import org.junit.Test;

import cn.addr.user.model.UserBean;
@SuppressWarnings("unchecked")
public class UserDao extends DaoBase<UserBean>{

	public UserDao(){
		super();
	}
	
	//SINGLETON
	private static class Singleton
	{
		public static UserDao instance = new UserDao(); 
	}
	
	public static UserDao getInstance(){
		return Singleton.instance;
	}

	public UserBean login(String username,String password){
		UserBean result = null;
		String hql = "FROM UserBean where username = ? and password = ?";
		Query query = this.createQuery(hql);
		query.setParameter(0, username);
		query.setParameter(1, password);
		List<UserBean> list = query.list();
		if(!list.isEmpty()){
			result = list.get(0);
		}
		return result;
	}

	@SuppressWarnings("unused")
	public UserBean register(String username,String password){
		UserBean result = null;//login(username, password);
		if(result==null){
			try {
				result = new UserBean(username, password);
				result.setUuid(UUID.randomUUID().toString());
				this.begin();
				this.save(result);
				this.commit();
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				this.close();
			}
			return result;
		}else{
			return null;
		}
	}
	
	@Test
	public void testTable(){
		UserBean user = new UserBean("kong","123");
		user.setUuid(UUID.randomUUID().toString());
		register("kong", "123");
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	protected Class classOfT() {
		// TODO Auto-generated method stub
		return UserBean.class;
	}
}
